<template>
  <el-dialog
    v-model="visible"
    :title="isLogin ? '登录后内容更精彩' : '注册新用户'"
    width="480px"
    center
    :close-on-click-modal="false"
  >
    <!-- 登录表单 -->
    <el-form
      v-if="isLogin"
      :model="loginForm"
      :rules="loginRules"
      ref="loginFormRef"
      label-width="80px"
      class="login-form"
    >
      <el-form-item prop="username" label="用户名">
        <el-input
          v-model="loginForm.username"
          placeholder="请输入用户名"
          size="large"
        />
      </el-form-item>
      <el-form-item prop="password" label="密码">
        <el-input
          v-model="loginForm.password"
          type="password"
          placeholder="请输入密码"
          size="large"
        />
      </el-form-item>
      <el-form-item>
        <div class="agreement-text">
          登录即同意 <a href="#">《用户协议》</a> 和
          <a href="#">《隐私政策》</a>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="handleLogin"
          :loading="loginLoading"
          class="submit-button"
        >
          登录
        </el-button>
      </el-form-item>
      <div class="form-footer">
        还没有账号？<a @click="switchForm(false)">立即注册</a>
      </div>
    </el-form>

    <!-- 注册表单 -->
    <el-form
      v-else
      :model="registerForm"
      :rules="registerRules"
      ref="registerFormRef"
      label-width="80px"
      class="register-form"
    >
      <el-form-item prop="username" label="用户名">
        <el-input
          v-model="registerForm.username"
          placeholder="请输入用户名（3-20个字符）"
          size="large"
        />
      </el-form-item>
      <el-form-item prop="password" label="密码">
        <el-input
          v-model="registerForm.password"
          type="password"
          placeholder="请输入密码（4-20个字符）"
          size="large"
        />
      </el-form-item>
      <el-form-item prop="confirmPassword" label="确认密码">
        <el-input
          v-model="registerForm.confirmPassword"
          type="password"
          placeholder="请再次输入密码"
          size="large"
        />
      </el-form-item>
      <el-form-item prop="email" label="邮箱">
        <el-input
          v-model="registerForm.email"
          placeholder="请输入邮箱"
          size="large"
        />
      </el-form-item>
      <el-form-item>
        <div class="agreement-text">
          注册即同意 <a href="#">《用户协议》</a> 和
          <a href="#">《隐私政策》</a>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="handleRegister"
          :loading="registerLoading"
          class="submit-button"
        >
          注册
        </el-button>
      </el-form-item>
      <div class="form-footer">
        已有账号？<a @click="switchForm(true)">立即登录</a>
      </div>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const router = useRouter()
const userStore = useUserStore()

// 控制对话框显示和表单切换
const visible = ref(false)
const isLogin = ref(true)

// 登录相关的响应式数据
const loginLoading = ref(false)
const loginFormRef = ref()

const loginForm = reactive({
  username: "",
  password: "",
})

const loginRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      min: 3,
      max: 20,
      message: "用户名长度应在3-20个字符之间",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 4, max: 20, message: "密码长度应在4-20个字符之间", trigger: "blur" },
  ],
}

// 注册相关的响应式数据
const registerLoading = ref(false)
const registerFormRef = ref()

const registerForm = reactive({
  username: "",
  password: "",
  confirmPassword: "",
  email: "",
})

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const registerRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      min: 3,
      max: 20,
      message: "用户名长度应在3-20个字符之间",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 4, max: 20, message: "密码长度应在4-20个字符之间", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    { validator: validatePass, trigger: "blur" }
  ],
  email: [
    { required: true, message: "请输入邮箱地址", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }
  ]
}

// 切换登录/注册表单
const switchForm = (toLogin) => {
  isLogin.value = toLogin
  // 重置表单
  if (toLogin) {
    loginForm.username = ""
    loginForm.password = ""
    if (loginFormRef.value) {
      loginFormRef.value.resetFields()
    }
  } else {
    registerForm.username = ""
    registerForm.password = ""
    registerForm.confirmPassword = ""
    registerForm.email = ""
    if (registerFormRef.value) {
      registerFormRef.value.resetFields()
    }
  }
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return;

  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loginLoading.value = true;
      try {
        const params = new URLSearchParams();
        params.append("username", loginForm.username);
        params.append("password", loginForm.password);

        const response = await axios.post("/app/auth/login", params);

        if (response.data.code === 200) {
          const { token, id, userName, avatar, userType } = response.data.data;

          // 构造用户信息对象
          const userInfo = {
            username: userName || loginForm.username,
            avatar: avatar || "",
            userType: userType || "1",
            id: id,
          };

          // 存储到sessionStorage
          try {
            sessionStorage.setItem("token", token);
            sessionStorage.setItem("userInfo", JSON.stringify(userInfo));
          } catch (storageError) {
            console.error("存储到sessionStorage失败:", storageError);
          }

          // 更新Pinia store
          userStore.setToken(token);
          userStore.setUserInfo(userInfo);

          ElMessage.success("登录成功");
          visible.value = false;

          // 重置表单
          loginForm.username = "";
          loginForm.password = "";
        } else {
          ElMessage.error(response.data.msg || "登录失败");
        }
      } catch (error) {
        console.error("登录失败:", error);
        ElMessage.error(error.response?.data?.msg || "登录失败");
      } finally {
        loginLoading.value = false;
      }
    }
  });
};

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return;

  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      registerLoading.value = true;
      try {
        const response = await axios.post("/app/auth/register", {
          username: registerForm.username,
          password: registerForm.password,
          email: registerForm.email
        });

        if (response.data.code === 200) {
          ElMessage.success("注册成功，请登录");
          switchForm(true); // 切换到登录表单
        } else {
          ElMessage.error(response.data.msg || "注册失败");
        }
      } catch (error) {
        console.error("注册失败:", error);
        ElMessage.error(error.response?.data?.msg || "注册失败");
      } finally {
        registerLoading.value = false;
      }
    }
  });
};

// 暴露方法给父组件
defineExpose({
  show: () => {
    visible.value = true;
    isLogin.value = true; // 默认显示登录表单
  },
  hide: () => {
    visible.value = false;
  }
});
</script>

<style scoped>
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  margin-right: 0;
  padding: 30px 20px 20px;
  text-align: center;
}

:deep(.el-dialog__title) {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

:deep(.el-dialog__body) {
  padding: 10px 40px 30px;
}

.login-form,
.register-form {
  .el-form-item {
    margin-bottom: 20px;
  }
}

:deep(.el-input__wrapper) {
  padding: 1px 15px;
}

:deep(.el-form-item__label) {
  color: #333;
  font-weight: 500;
}

.agreement-text {
  text-align: center;
  color: #666;
  font-size: 14px;
}

.agreement-text a {
  color: #1890ff;
  text-decoration: none;
}

.agreement-text a:hover {
  color: #40a9ff;
}

.submit-button {
  width: 100%;
  height: 40px;
  font-size: 16px;
  background-color: #f85959;
  border-color: #f85959;
}

.submit-button:hover {
  background-color: #ff7070;
  border-color: #ff7070;
}

:deep(.el-dialog__footer) {
  display: none;
}

.form-footer {
  text-align: center;
  margin-top: 15px;
  color: #666;
  font-size: 14px;
}

.form-footer a {
  color: #f85959;
  text-decoration: none;
  cursor: pointer;
  margin-left: 5px;
}

.form-footer a:hover {
  color: #ff7070;
}
</style> 